<!--
  Basic login menu, checks username and password, and sets 'user_type' (admin, teacher or student) in $_SESSION.
-->
<?php
$root = $_SERVER['DOCUMENT_ROOT'];
include($root . "/util/config.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST"){
	$username=mysqli_real_escape_string($db,$_POST['username']);
	$password=mysqli_real_escape_string($db,$_POST['password']);
	$sql_query="SELECT password FROM users WHERE username = '$username'";
	$result=mysqli_query($db,$sql_query);
	$res_arr=mysqli_fetch_array($result,MYSQLI_ASSOC);
	$hash=$res_arr['password'];
	if(password_verify($password,$hash)){
		$sql_query="select usertype from users where username = '$username'";
		$result=mysqli_query($db,$sql_query);
		$_SESSION['login_user'] = $username;
		$res_arr=mysqli_fetch_array($result,MYSQLI_ASSOC);
		$auth_level=$res_arr['usertype'];
		$_SESSION['user_type'] = $auth_level;
		switch($auth_level){
			case "admin":
				header("location: admin/admin.php");
				break;
			case "teacher":
				header("location: teacher/teacher.php");
				break;
			case "student":
				header("location: student/student.php");
				break;
		}
	}
	else{
		$error = "Invalid username or password";
	}
}
?>
<html>
	<head>
		<title>Noodle Login</title>
		<style type = "text/css">
		body {
		   font-family:Arial, Helvetica, sans-serif;
		   font-size:14px;
		}
		label {
		   font-weight:bold;
		   width:100px;
		   font-size:14px;
		}
		.box {
		   border:#666666 solid 1px;
		}
		.center {
			display: block;
			margin-left: auto;
			margin-right: auto;
			width: 30%;
		}
		</style>
	</head>
   <body bgcolor = "#FFFFFF">
		<img src="/img/logo.png" alt="Logo" class="center">
		<div align = "center">
			<div style = "width:300px; border: solid 1px #333333; " align = "left">
				<div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Login</b></div>
					<div style = "margin:30px">
						<form action = "login.php" method = "post">
							<label>User Name  :</label><br/><input type = "text" name = "username" class = "box" /><br /><br />
							<label>Password   :</label><br/><input type = "password" name = "password" class = "box" /><br/><br />
							<input type = "submit" value = " Login "/><br />
						</form>
					<div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php if(isset($error)){echo $error;} ?></div>
				</div>
			</div>
		</div>
	</body>
</html>
